<template>
  <div class="history-view">
    <div class="header-container">
      <h1 class="page-title">项目历史<span class="accent">记录</span></h1>
      <p class="subtitle">查看所有项目的历史状态变更和操作记录</p>
    </div>
    
    <div v-if="loading" class="loading-state">
      <div class="loading-indicator">
        <div class="loading-circle"></div>
      </div>
      <p>加载历史数据中</p>
    </div>
    
    <div v-else-if="error" class="error-state">
      <div class="icon">
        <svg viewBox="0 0 24 24" width="40" height="40">
          <path fill="currentColor" d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z"/>
        </svg>
      </div>
      <p class="message">{{ error }}</p>
      <button @click="fetchAllProjects" class="retry-button">重新加载</button>
    </div>
    
    <div v-else-if="projects.length === 0" class="empty-state">
      <div class="icon">
        <svg viewBox="0 0 24 24" width="48" height="48">
          <path fill="currentColor" d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-5 14h-2v-2h2v2zm0-4h-2V7h2v6z"/>
        </svg>
      </div>
      <h2>暂无历史记录</h2>
      <p>目前没有任何项目历史记录。当您创建、更新或删除项目时，记录将显示在这里。</p>
    </div>
    
    <div v-else class="history-content">
      <div class="filter-panel">
        <div class="filter-header">
          <h2 class="filter-title">筛选条件</h2>
          <button class="reset-button" @click="resetFilters">
            <svg viewBox="0 0 24 24" width="16" height="16">
              <path fill="currentColor" d="M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z"/>
            </svg>
            <span>重置筛选</span>
          </button>
        </div>
        
        <div class="filter-grid">
          <div class="filter-group">
            <label for="projectFilter">项目 ID</label>
            <div class="select-wrapper">
              <select id="projectFilter" v-model="projectFilter">
                <option value="">所有项目</option>
                <option v-for="projectId in distinctProjectIds" :key="projectId" :value="projectId">
                  项目 #{{ projectId }}
                </option>
              </select>
              <svg class="select-arrow" viewBox="0 0 24 24" width="18" height="18">
                <path fill="currentColor" d="M7 10l5 5 5-5z"/>
              </svg>
            </div>
          </div>
          
          <div class="filter-group">
            <label for="statusFilter">项目状态</label>
            <div class="select-wrapper">
              <select id="statusFilter" v-model="statusFilter">
                <option value="">所有状态</option>
                <option value="0">进行中</option>
                <option value="2">已完成</option>
                <option value="3">已删除</option>
              </select>
              <svg class="select-arrow" viewBox="0 0 24 24" width="18" height="18">
                <path fill="currentColor" d="M7 10l5 5 5-5z"/>
              </svg>
            </div>
          </div>
        </div>
      </div>
      
      <div class="records-list">
        <div 
          v-for="(project, index) in filteredProjects" 
          :key="project.id" 
          class="record-card"
          :style="{'--animation-delay': `${index * 0.05}s`}"
        >
          <div class="card-header">
            <div class="project-id">#{{ project.id }}</div>
            <div class="status-badge" :class="getStatusClass(project.status)">
              {{ getStatusText(project.status) }}
            </div>
          </div>
          
          <div class="card-body">
            <h3 class="project-title">{{ project.title || '未命名项目' }}</h3>
            <div class="project-info">
              <div class="info-item">
                <svg viewBox="0 0 24 24" width="16" height="16">
                  <path fill="currentColor" d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"/>
                </svg>
                <span>{{ project.researcherInfo || '未指定研究者' }}</span>
              </div>
              
              <div class="info-item">
                <svg viewBox="0 0 24 24" width="16" height="16">
                  <path fill="currentColor" d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8z"/>
                </svg>
                <span>创建于: {{ formatDate(project.createdAt) }}</span>
              </div>
              
              <div v-if="project.isDeleted" class="info-item deleted-info">
                <svg viewBox="0 0 24 24" width="16" height="16">
                  <path fill="currentColor" d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"/>
                </svg>
                <span>删除于: {{ formatDate(project.deletedAt) }}</span>
              </div>
              
              <div v-if="project.isDeleted" class="info-item reason-info">
                <svg viewBox="0 0 24 24" width="16" height="16">
                  <path fill="currentColor" d="M11 7h2v2h-2zm0 4h2v6h-2zm1-9C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"/>
                </svg>
                <span>删除原因: {{ project.deletionReason || '无' }}</span>
              </div>
              
              <div v-if="project.isCompleted" class="info-item completed-info">
                <svg viewBox="0 0 24 24" width="16" height="16">
                  <path fill="currentColor" d="M9 16.2L4.8 12l-1.4 1.4L9 19 21 7l-1.4-1.4L9 16.2z"/>
                </svg>
                <span>已完成</span>
              </div>
              
              <div class="project-description">
                {{ truncateText(project.description, 120) || '无项目描述' }}
              </div>
            </div>
          </div>
          
          <div class="card-footer">
            <router-link :to="`/project/${project.id}`" class="view-button">
              <span>查看详情</span>
              <svg viewBox="0 0 24 24" width="16" height="16">
                <path fill="currentColor" d="M8.59 16.59L13.17 12 8.59 7.41 10 6l6 6-6 6-1.41-1.41z"/>
              </svg>
            </router-link>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'HistoryList',
  data() {
    return {
      loading: true,
      error: null,
      projects: [],
      projectFilter: '',
      statusFilter: ''
    }
  },
  computed: {
    distinctProjectIds() {
      const projectIds = new Set();
      this.projects.forEach(project => {
        if (project && project.id) {
          projectIds.add(project.id);
        }
      });
      return Array.from(projectIds).sort((a, b) => a - b);
    },
    
    filteredProjects() {
      return this.projects.filter(project => {
        // 确保项目对象有效
        if (!project || !project.id) return false;
        
        // 项目ID筛选
        if (this.projectFilter && project.id != this.projectFilter) {
          return false;
        }
        
        // 状态筛选
        if (this.statusFilter !== '' && project.status != this.statusFilter) {
          return false;
        }
        
        return true;
      });
    }
  },
  async created() {
    await this.fetchAllProjects();
  },
  methods: {
    async fetchAllProjects() {
      try {
        this.loading = true;
        const response = await this.$store.dispatch('fetchAllProjects')
          .catch(error => {
            console.error('fetchAllProjects失败，回退到fetchProjects:', error);
            return this.$store.dispatch('fetchProjects');
          });
        
        if (response && response.success) {
          this.projects = response.projects || [];
        } else {
          this.error = '获取项目历史记录失败';
          this.projects = [];
        }
      } catch (error) {
        console.error('获取项目历史记录错误:', error);
        this.error = error.response?.data || '获取项目历史记录失败';
        this.projects = [];
      } finally {
        this.loading = false;
      }
    },
    
    resetFilters() {
      this.projectFilter = '';
      this.statusFilter = '';
    },
    
    getStatusClass(status) {
      switch(parseInt(status)) {
        case 0:
          return 'status-active';
        case 2:
          return 'status-completed';
        case 3:
          return 'status-deleted';
        default:
          return 'status-unknown';
      }
    },
    
    getStatusText(status) {
      switch(parseInt(status)) {
        case 0:
          return '进行中';
        case 2:
          return '已完成';
        case 3:
          return '已删除';
        default:
          return '未知状态';
      }
    },
    
    truncateText(text, maxLength) {
      if (!text) return '';
      return text.length > maxLength ? text.substring(0, maxLength) + '...' : text;
    },
    
    formatDate(timestamp) {
      if (!timestamp) return '时间未记录';
      
      try {
        // 处理不同格式的时间戳
        let date;
        if (typeof timestamp === 'string') {
          // 如果是字符串格式，尝试转为数字
          date = new Date(parseInt(timestamp));
          
          // 检查是否是有效日期
          if (isNaN(date.getTime())) {
            // 尝试直接作为日期字符串解析
            date = new Date(timestamp);
          }
        } else if (timestamp instanceof Date) {
          // 如果已经是Date对象
          date = timestamp;
        } else {
          // 其他情况尝试作为数字
          date = new Date(parseInt(timestamp));
        }
        
        // 检查最终的日期是否有效
        if (isNaN(date.getTime())) {
          return '无效日期';
        }
        
        return date.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        }).replace(/\//g, '-');
      } catch (e) {
        console.error('时间格式化错误:', e, timestamp);
        return '格式错误';
      }
    }
  }
}
</script>

<style scoped>
:root {
  --color-primary: #446DF6;
  --color-primary-light: #5D80F9;
  --color-primary-dark: #3A5FD9;
  --color-accent: #FF5757;
  --color-accent-light: #FF7676;
  --color-accent-dark: #E64545;
  --color-success: #2AB280;
  --color-warning: #F2BD59;
  --color-error: #EF476F;
  --color-dark: #243252;
  --color-light: #fff;
  --color-gray-50: #F9FAFB;
  --color-gray-100: #F3F4F7;
  --color-gray-200: #E6E8EF;
  --color-gray-300: #D1D5E1;
  --color-gray-400: #9CA3AF;
  --color-gray-500: #6B7280;
  --color-gray-600: #4B5563;
  --color-gray-700: #374151;
  --color-gray-800: #1F2937;
  --color-gray-900: #111827;
  
  --shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.05);
  --shadow-md: 0 4px 6px rgba(0, 0, 0, 0.08);
  --shadow-lg: 0 10px 15px rgba(0, 0, 0, 0.08);
  --shadow-xl: 0 20px 25px rgba(0, 0, 0, 0.08);
  
  --transition-fast: 0.15s ease-in-out;
  --transition-normal: 0.25s ease-in-out;
  --transition-slow: 0.4s cubic-bezier(0.19, 1, 0.22, 1);
  
  --border-radius-sm: 0.25rem;
  --border-radius-md: 0.375rem;
  --border-radius-lg: 0.5rem;
  --border-radius-xl: 0.75rem;
}

.history-view {
  max-width: 1200px;
  margin: 0 auto;
  padding: 3rem 1.5rem;
  color: var(--color-dark);
  font-family: 'Inter', system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
  background-color: var(--color-gray-50);
}

/* Header Styles */
.header-container {
  text-align: center;
  margin-bottom: 3rem;
  position: relative;
  padding: 2rem;
  border-radius: var(--border-radius-lg);
  background: linear-gradient(135deg, #EFF4FF 0%, #F6F8FF 100%);
  box-shadow: var(--shadow-sm);
}

.page-title {
  font-size: clamp(2rem, 5vw, 3rem);
  font-weight: 800;
  margin-bottom: 1rem;
  letter-spacing: -0.02em;
  color: var(--color-dark);
}

.accent {
  background: linear-gradient(135deg, var(--color-primary), var(--color-primary-light));
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  color: transparent;
}

.subtitle {
  font-size: 1.125rem;
  color: var(--color-gray-600);
  max-width: 600px;
  margin: 0 auto;
}

/* Loading State */
.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  color: var(--color-gray-600);
  background-color: white;
  border-radius: var(--border-radius-lg);
  box-shadow: var(--shadow-md);
  margin-bottom: 2rem;
}

.loading-indicator {
  margin-bottom: 1.5rem;
}

.loading-circle {
  width: 40px;
  height: 40px;
  border: 3px solid var(--color-gray-200);
  border-top-color: var(--color-primary);
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

/* Error State */
.error-state {
  padding: 3rem 2rem;
  background-color: white;
  border-radius: var(--border-radius-lg);
  box-shadow: var(--shadow-md);
  text-align: center;
  max-width: 500px;
  margin: 0 auto;
  border-top: 5px solid var(--color-error);
}

.error-state .icon {
  color: var(--color-error);
  margin-bottom: 1.5rem;
}

.error-state .message {
  color: var(--color-gray-700);
  margin-bottom: 1.5rem;
}

.retry-button {
  background-color: var(--color-primary);
  color: white;
  font-weight: 600;
  padding: 0.75rem 1.5rem;
  border: none;
  border-radius: var(--border-radius-md);
  cursor: pointer;
  transition: all var(--transition-fast);
  box-shadow: 0 4px 6px rgba(68, 109, 246, 0.2);
}

.retry-button:hover {
  background-color: var(--color-primary-dark);
  transform: translateY(-2px);
  box-shadow: 0 6px 10px rgba(68, 109, 246, 0.3);
}

/* Empty State */
.empty-state {
  padding: 3rem 2rem;
  background-color: white;
  border-radius: var(--border-radius-lg);
  box-shadow: var(--shadow-md);
  text-align: center;
  max-width: 500px;
  margin: 0 auto;
  border-top: 5px solid var(--color-primary);
}

.empty-state .icon {
  color: var(--color-gray-400);
  margin-bottom: 1.5rem;
}

.empty-state h2 {
  font-size: 1.5rem;
  font-weight: 700;
  margin-bottom: 1rem;
  color: var(--color-dark);
}

.empty-state p {
  color: var(--color-gray-600);
  max-width: 400px;
  margin: 0 auto;
}

/* Filter Panel */
.filter-panel {
  background: linear-gradient(135deg, #FFFFFF 0%, #F8FAFF 100%);
  border-radius: var(--border-radius-lg);
  box-shadow: var(--shadow-md);
  padding: 1.5rem;
  margin-bottom: 2rem;
  transition: transform var(--transition-normal);
  border: 1px solid var(--color-gray-200);
}

.filter-panel:hover {
  transform: translateY(-3px);
  box-shadow: var(--shadow-lg);
}

.filter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
  padding-bottom: 1rem;
  border-bottom: 1px solid var(--color-gray-200);
}

.filter-title {
  font-size: 1.25rem;
  font-weight: 700;
  color: var(--color-dark);
  margin: 0;
  position: relative;
  padding-left: 1rem;
}

.filter-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  height: 1.25rem;
  width: 4px;
  background: linear-gradient(to bottom, var(--color-primary), var(--color-primary-light));
  border-radius: 2px;
}

.reset-button {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  background-color: var(--color-gray-100);
  border: none;
  padding: 0.5rem 1rem;
  border-radius: var(--border-radius-md);
  font-size: 0.875rem;
  color: var(--color-gray-700);
  cursor: pointer;
  transition: all var(--transition-fast);
}

.reset-button:hover {
  background-color: var(--color-gray-200);
  color: var(--color-gray-800);
}

.reset-button svg {
  transition: transform var(--transition-normal);
}

.reset-button:hover svg {
  transform: rotate(-45deg);
}

.filter-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 1.5rem;
}

.filter-group {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.filter-group label {
  font-size: 0.875rem;
  font-weight: 600;
  color: var(--color-dark);
}

.select-wrapper {
  position: relative;
}

.select-wrapper select {
  width: 100%;
  padding: 0.75rem 1rem;
  font-size: 1rem;
  border: 1px solid var(--color-gray-300);
  border-radius: var(--border-radius-md);
  background-color: white;
  appearance: none;
  color: var(--color-gray-800);
  transition: border-color var(--transition-fast), box-shadow var(--transition-fast);
}

.select-wrapper select:focus {
  border-color: var(--color-primary);
  box-shadow: 0 0 0 3px rgba(68, 109, 246, 0.15);
  outline: none;
}

.select-arrow {
  position: absolute;
  right: 1rem;
  top: 50%;
  transform: translateY(-50%);
  color: var(--color-gray-500);
  pointer-events: none;
}

/* Records List */
.records-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 1.5rem;
}

.record-card {
  background-color: white;
  border-radius: var(--border-radius-lg);
  box-shadow: var(--shadow-md);
  overflow: hidden;
  transition: all var(--transition-normal);
  display: flex;
  flex-direction: column;
  opacity: 0;
  transform: translateY(20px);
  animation: fadeIn 0.6s forwards;
  animation-delay: var(--animation-delay);
  border: 1px solid var(--color-gray-200);
}

@keyframes fadeIn {
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.record-card:hover {
  transform: translateY(-5px) scale(1.01);
  box-shadow: var(--shadow-xl);
  border-color: var(--color-gray-300);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem 1.5rem;
  border-bottom: 1px solid var(--color-gray-200);
  background: linear-gradient(to right, rgba(68, 109, 246, 0.03), rgba(93, 128, 249, 0.05));
}

.project-id {
  font-family: 'Courier New', monospace;
  font-weight: bold;
  color: var(--color-primary);
  font-size: 0.875rem;
}

.status-badge {
  padding: 0.25rem 0.75rem;
  border-radius: 100px;
  font-size: 0.75rem;
  font-weight: 700;
  letter-spacing: 0.025em;
  text-transform: uppercase;
}

.status-active {
  background-color: rgba(68, 109, 246, 0.1);
  color: var(--color-primary);
  border: 1px solid rgba(68, 109, 246, 0.2);
}

.status-completed {
  background-color: rgba(42, 178, 128, 0.1);
  color: var(--color-success);
  border: 1px solid rgba(42, 178, 128, 0.2);
}

.status-deleted {
  background-color: rgba(239, 71, 111, 0.1);
  color: var(--color-error);
  border: 1px solid rgba(239, 71, 111, 0.2);
}

.status-unknown {
  background-color: rgba(107, 114, 128, 0.1);
  color: var(--color-gray-600);
  border: 1px solid rgba(107, 114, 128, 0.2);
}

.card-body {
  padding: 1.5rem;
  flex: 1;
}

.project-title {
  font-size: 1.25rem;
  font-weight: 700;
  margin: 0 0 1rem;
  color: var(--color-dark);
}

.project-info {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 0.875rem;
  color: var(--color-gray-600);
}

.info-item svg {
  flex-shrink: 0;
  color: var(--color-primary-light);
}

.deleted-info svg {
  color: var(--color-error);
}

.reason-info svg {
  color: var(--color-warning);
}

.completed-info svg {
  color: var(--color-success);
}

.project-description {
  margin-top: 1rem;
  padding-top: 1rem;
  border-top: 1px solid var(--color-gray-200);
  font-size: 0.875rem;
  color: var(--color-gray-600);
  line-height: 1.5;
}

.card-footer {
  padding: 1rem 1.5rem;
  background-color: var(--color-gray-50);
  border-top: 1px solid var(--color-gray-200);
}

.view-button {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  width: 100%;
  padding: 0.75rem 1rem;
  background: linear-gradient(135deg, #F8FAFF 0%, #FFFFFF 100%);
  color: var(--color-primary);
  border: 1px solid var(--color-gray-200);
  border-radius: var(--border-radius-md);
  text-decoration: none;
  font-weight: 600;
  font-size: 0.875rem;
  transition: all var(--transition-fast);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.03);
}

.view-button:hover {
  background: linear-gradient(135deg, var(--color-primary), var(--color-primary-light));
  color: white;
  border-color: var(--color-primary);
  box-shadow: 0 4px 8px rgba(68, 109, 246, 0.25);
}

.view-button svg {
  transition: transform var(--transition-fast);
}

.view-button:hover svg {
  transform: translateX(3px);
}

/* Responsive Design */
@media (max-width: 768px) {
  .history-view {
    padding: 2rem 1rem;
  }
  
  .records-list {
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  }
}
</style> 